function getRequestBasePath() {
  var pathName = window.document.location.pathname;
  var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
  return projectName;
}
var ajaxRequestBasePath = getRequestBasePath();

function ajaxRequest(url, data, hasResult, hasAlert) {
  if (data === undefined) {
    data = {};
  }

  if (hasResult === undefined) {
    hasResult = true;
  }
  if (hasAlert === undefined) {
    hasAlert = true;
  }
  return new Promise(function (resole, reject) {
    var $alert;
    if (window.Vue !== undefined) {
      $alert = Vue.prototype.$alert;
    }
    $.ajax({
      url: ajaxRequestBasePath + '/' + url,
      type: 'POST',
      data: data,
      dataType: 'json',
      timeout: 5 * 60 * 1000,
      success: function (res) {
        var result = res.result;
        var data;
        if (!hasResult) {
          if (result === undefined) {
            result = true;
          }
          data = res;
        } else {
          data = res.data;
        }

        if (!result && hasResult && hasAlert) {
          if ($alert !== undefined) {
            $alert(res.info, '信息', {
              dangerouslyUseHTMLString: true
            });
          }
          reject({
            textStatus: res.info
          });
          return;
        }
        resole(data);
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        if ($alert !== undefined && hasAlert) {
          var readyState = XMLHttpRequest.readyState;
          var status = XMLHttpRequest.status;
          var msg;
          if (readyState === 0 && status === 0) {
            msg = '请求超时';
          } else {
            msg = `请求失败：readyState-${readyState},status-${status}`;
          }
          $alert(msg, '信息', {
            dangerouslyUseHTMLString: true
          });
        }
        reject({
          XMLHttpRequest: XMLHttpRequest,
          textStatus: textStatus,
          errorThrown: errorThrown
        });
      }
    });
  });
}

function postImgsToQiniu(tokenUrl, files) {
  var baseImgURL = 'https://upload.shinehao.com.cn';
  if (!_.isArray(files)) {
    files = [files];
  }

  var uploadImg = function (file, token) {
    var name = file.name;
    var blob = file.blob;
    return new Promise(function (resolve, reject) {
      var key = `${moment().format('YYYYMMDDHHmmss')}${name}`;
      var observable = qiniu.upload(blob, key, token, {
        fname: name,
        params: {}
      }, {
        useCdnDomain: true,
        disableStatisticsReport: true
      });

      var id = file.id;
      observable.subscribe({
        error: function (errorObj) {
          if (id === undefined) {
            resolve(errorObj);
          } else {
            resolve({
              id: id,
              error: errorObj
            });
          }
        },
        complete: function (res) {
          var key = res.key;
          var imgUrl = `${baseImgURL}/${key}`;
          if (id === undefined) {
            resolve(imgUrl);
          } else {
            resolve({
              id: id,
              url: imgUrl
            });
          }
        }
      });
    });
  };

  return new Promise(function (resolve, reject) {
    ajaxRequest(tokenUrl).then(function (token) {
      var promiseList = [];
      for (var i = 0; i < files.length; i++) {
        var file = files[i];
        promiseList.push(uploadImg(file, token));
      }
      Promise.all(promiseList).then(function (fileUrlList) {
        resolve(fileUrlList);
      });
    }).catch(function (error) {
      reject(error);
    });
  });
}

function getFileImgSize(file) {
  return new Promise(function (resole) {
    var reader = new FileReader();
    reader.onload = function (e) {
      var data = e.target.result;
      var image = new Image();
      image.onload = function () {
        var width = image.width;
        var height = image.height;
        resole({
          width: width,
          height: height
        });
      };
      image.src = data;
    };
    reader.readAsDataURL(file);
  });
}

function postImgFileToQiniu(tokenUrl, file, callback, hasWatermark,isCompress) {
  var baseImgURL = 'https://upload.shinehao.com.cn';
  return new Promise(function (resolve, reject) {
    ajaxRequest(tokenUrl).then(function (token) {
      var name = file.name;
      var key = `${moment().format('YYYYMMDDHHmmss')}${name}`;
      getFileImgSize(file).then(function (size) {
        var flag = false;
        if (isCompress) {
          flag = size.width > 1000 || size.height > 1000;
        }
        var observable = qiniu.upload(file, key, token, {
          fname: name,
          params: {}
        }, {
          useCdnDomain: true,
          disableStatisticsReport: true
        });
        observable.subscribe({
          next: function (event) {
            if (callback !== undefined) {
              callback(event.total.percent);
            }
          },
          complete: function (res) {
            var key = res.key;
            var imgUrl = `${baseImgURL}/${key}`;
            if (flag) {
              imgUrl += '?imageMogr/thumbnail/1000x1000/auto-orient'
            }
            // if (hasWatermark) {
            //   waterMarkUrl = qiniu.watermark({
            //     mode: 2,
            //     text: key,
            //     dissolve: 1,
            //     fontsize: 800,
            //     font: '仿宋',
            //     dx: 0,
            //     dy: 0,
            //     fill: '#ff0000'
            //   });
            //   imgUrl += `?${waterMarkUrl}`;
            // }
            resolve(imgUrl);
          },
          error: function (error) {
            reject(error)
          }
        });
      });
    }).catch(function (error) {
      reject(error);
    });
  });
}

function postFileToQiniu(tokenUrl, file, callback) {
  var baseImgURL = 'https://upload.shinehao.com.cn';
  return new Promise(function (resolve, reject) {
    ajaxRequest(tokenUrl).then(function (token) {
      var name = file.name;
      var key = `${moment().format('YYYYMMDDHHmmss')}${name}`;
      var observable = qiniu.upload(file, key, token, {
        fname: name,
        params: {}
      }, {
        useCdnDomain: true,
        disableStatisticsReport: true
      });
      observable.subscribe({
        next: function (event) {
          if (callback !== undefined) {
            callback(event.total.percent);
          }
        },
        complete: function (res) {
          var key = res.key;
          var imgUrl = `${baseImgURL}/${key}`;
          resolve(imgUrl);
        },
        error: function (error) {
          reject(error)
        }
      });
    }).catch(function (error) {
      reject(error);
    });
  });
}

function ajaxCssFile(url) {
  return new Promise(function (resole, reject) {
    if (url.startsWith('/')) {
      url = ajaxRequestBasePath + url;
    }
    $.ajax({
      url: url,
      type: 'POST',
      dataType: 'text',
      success: function (cssText) {
        resole(cssText);
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        reject({
          textStatus: textStatus,
          errorThrown: errorThrown
        });
      }
    });
  });
}

function ajaxCssFiles(urlList) {
  var promiseList = _.map(urlList, function (url) {
    return ajaxCssFile(url);
  });

  return Promise.all(promiseList).then(function (cssStyles) {
    cssStyles = _.map(cssStyles, function (cssStyle) {
      return cssStyle.replace(/\n(\s+)?/g, "");
    });
    return cssStyles;
  });
}

function ajaxFile(url, data) {
  if (data === undefined) {
    data = {};
  }
  if (url.startsWith('/')) {
    url = ajaxRequestBasePath + url;
  }
  return new Promise(function (resole, reject) {
    $.ajax({
      url: url,
      type: 'POST',
      data: data,
      dataType: 'text',
      success: function (fileText) {
        resole(fileText);
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        reject({
          textStatus: textStatus,
          errorThrown: errorThrown
        });
      }
    });
  });
}
